package com.zhangck.bos2_0.Service.take_delivery.Impl;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhangck.bos2_0.Service.take_delivery.OrderService;
import com.zhangck.bos2_0.dao.AreaRepository;
import com.zhangck.bos2_0.dao.FixedAreaRepoistory;
import com.zhangck.bos2_0.dao.OrderRepository;
import com.zhangck.bos2_0.dao.WorkBillRepoistory;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;

/** 
* @author 上午茶
* @version 创建时间：2018年6月11日 下午3:34:34 
* 类说明 
*/
@Service
@Transactional
public class OrderServicesImpl implements OrderService {

	@Autowired
	private OrderRepository OrderReposittory;
	
	@Autowired
	private WorkBillRepoistory workBillRepoistory;
	
	@Autowired
	private FixedAreaRepoistory fixedAreaRepoistory;
	
	@Autowired
	private AreaRepository areaRepository;
	
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Override
	public void saveOrder(Order order) {
		System.out.println("进来了aaaaaaaaaaaaaa");
		System.out.println(order.getSendCompany()+"aaaa");
		
		order.setOrderNum(UUID.randomUUID().toString());//设置订单号	
		order.setOrderTime(new Date());//设置订单时间
		order.setStatus("1");//设置订单的状态
		order.setOrderType("1");//自动分单
		
		// 寄件人 省市区
		Area area = order.getSendArea();
		Area persistArea = areaRepository.findByProvinceAndCityAndDistrict(
				area.getProvince(), area.getCity(), area.getDistrict());

		// 收件人 省市区
		Area recArea = order.getRecArea();
		Area persistRecArea = areaRepository
				.findByProvinceAndCityAndDistrict(recArea.getProvince(),
						recArea.getCity(), recArea.getDistrict());
		
		order.setSendArea(persistArea);
		order.setRecArea(persistRecArea);
		
		//根据寄件地址找到定区ID
		String fiexAreaID = WebClient.create("http://127.0.0.1:8088/services/customerService/Customer/getFixeArea?address="+order.getSendAddress())
		.accept(MediaType.APPLICATION_JSON).get(String.class);
		
		if (fiexAreaID!=null) {
			//根据定区ID找到定区，在找到快递员
			FixedArea fixedArea = fixedAreaRepoistory.findOne(fiexAreaID);
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			if (iterator.hasNext()) {
				Courier courier = iterator.next();
				System.out.println("自动分单成功");
				order.setCourier(courier);
				OrderReposittory.save(order);
				System.out.println("保存成功");
				return;
			}
		}
			
			Area area1 = order.getSendArea();
			Area area2 = areaRepository.findByProvinceAndCityAndDistrict(area1.getProvince(),area1.getCity(),area1.getDistrict());
			Set<SubArea> subareas = area2.getSubareas();//获取全部分区
			//1.判断是否包含关键字
			for (SubArea subArea : subareas) {
				//判断客户的下单地址是否包含了分区的关键字
				if (order.getSendAddress().contains(subArea.getKeyWords())) {
					//通过分区找到定区，定区在找到快递员
					Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
					if (iterator.hasNext()) {
						Courier courier = iterator.next();
						System.out.println("自动分单成功");
						order.setCourier(courier);
						OrderReposittory.save(order);
						System.out.println("保存成功");
						return;
					}
				}
			}
			//2.判断是否包含辅助关键字
			for (SubArea subArea : subareas) {
				//判断客户下单的地址是否包含了辅助关键字
				if (order.getSendAddress().contains(subArea.getKeyWords())) {
					//通过分区找到定区，定区在找到快递员
					Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
					if (iterator.hasNext()) {
						Courier courier = iterator.next();
						System.out.println("自动分单成功");
						order.setCourier(courier);
						OrderReposittory.save(order);
						System.out.println("保存成功");
						return;
					}
				}
			}
			order.setOrderType("2");//进入人工分单
			OrderReposittory.save(order);
	}

	public void getWorkBill(final Order order){
		WorkBill workBill = new WorkBill();
		workBill.setCourier(order.getCourier());
		workBill.setType("新");
		workBill.setBuildtime(new Date());
		workBill.setPickstate("新单");
		workBill.setOrder(order);
		workBill.setRemark(order.getRemark());//备注
		final String numeric = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(numeric);
		workBillRepoistory.save(workBill);
		
		jmsTemplate.send("smsWorkBill" ,new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("msg", "短信序号："+numeric+"取件地址："+order.getSendAddress()
				+"联系人:"+order.getSendName()+"手机号为："+order.getTelephone()+"快递员捎话："+order.getSendMobileMsg());
				return mapMessage;
			}
		});
		workBill.setPickstate("已通知");
	}
	
}
